<?php
	// Redirect user to certain link that predefine
    require_once 'config/config.php';
	require_once 'inc/db.php';
	require_once 'inc/get_country_from_ip.php';

	// Get link from database
	if (isset($_GET['code'])) {
		$code = $_GET['code'];
		$query = "SELECT id, normal_link, certain_link FROM newsletter_links WHERE code = ?";
		$stmt = $mysqli->prepare($query);
		$linkId = "";
		$normalLink = "";
		$certainLink = "";
		if ($stmt) {
			$stmt->bind_param("s",$code);
			$stmt->execute();
			$stmt->bind_result($linkId,$normalLink,$certainLink);
			$stmt->fetch();
			$stmt->close();
		}else{
			die("Error1: ".$query);
		}

		// Get visitor country, city from IP
		// fake ip for test
        // $ip = '113.178.39.141';
		$visitor = "Visitor";
		// $visitor = "113.178.39.141";
		$countryCode = ip_info($visitor, "Country Code");
		$country = ip_info($visitor, "Country");
		$region = ip_info($visitor, "Region");
		$city = ip_info($visitor, "City");

		// Detect visitor IP
		$ip = $_SERVER["REMOTE_ADDR"];
        if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        
        

        // Save user info to database
        if (isset($linkId)) {
        	$redirectLink = '';
        	if (isset($certainLink) && isset($normalLink)) {
        		if(checkCertainLocation($countryCode, $city)){
					$redirectLink = $certainLink;
				}else{
					$redirectLink = $normalLink;
				}
        	}else{
				header("Location: ".DEFAULT_LINK);
			}
        	$newQuery = "INSERT INTO newsletter_visitors(ip, city, country, region, link_redirected, link_id, datetime) VALUES(?,?,?,?,?,?,NOW())";
	        $stmt = $mysqli->prepare($newQuery);
	        if ($stmt) {
	        	$stmt->bind_param("sssssi",$ip,$city, $countryCode, $region, $redirectLink,$linkId);
	        	$result = $stmt->execute();
				$stmt->close();
	        	if($result){
		            echo 'success';
		        }else{
		            die("Error: ".$newQuery);
		        }
	        }else{
	        	die($mysqli->error);
	        }
			header("Location: ".$redirectLink);
        }else{
			header("Location: ".DEFAULT_LINK);
        }
		
	}else{
		header("Location: ".DEFAULT_LINK);
	}


	function checkCertainLocation($countryCode, $city)
	{
		global $mysqli;
		$query = "SELECT city from newsletter_certain_nearby WHERE country_code = ?";
		$stmt = $mysqli->prepare($query);
	    if ($stmt) {
	    	$stmt->bind_param("s",$countryCode);
	        if($stmt->execute()){
	            $stmt->bind_result($cityDb);
				$ok = false;
	            while($stmt->fetch()){
	            	$stmt->bind_result($cityDb);
	            	if(normalizeString($cityDb) == normalizeString($city)){
	            		$ok = true;
	            		break;
	            	}
	            }
	            if ($ok) {
	            	return true;
	            }
	            $stmt->close();
	        }
	    }else{
	        die("Error:  ".$query);
	    }
		// Check nearby
		$query = "SELECT place FROM newsletter_nearest";
		$stmt = $mysqli->prepare($query);
		if($stmt){
			$stmt->execute();
			$stmt->bind_result($place);
			$ok = false;
			while ($stmt->fetch()) {
				if($city == $place) {
					$ok = true;
					break;
				}
			}
			return $ok;
		}else{
			echo "Error: ".$query;
		}
			
		return false;
	}
	function normalizeString($str)
	{
	    return str_replace(array("\n", "\t", " ", "-", "_"), NULL, strtolower(trim($str)));
	}
?>